package com.timo.shopp.common.util;

import com.timo.shopp.common.constants.ResultCode;
import lombok.Data;

import java.io.Serializable;
import java.util.Optional;

/**
 * @Author: Timo
 * @Date: 2019/3/23 11:41
 * @Description: 响应返回的实体类
 */
@Data
public class Result<T> implements Serializable {
    /**
     * 返回的数据
     */
    private T data;
    /**
     * 响应 true 成功 / false 失败
     */
    private Boolean isSuccess;
    /**
     * 返回状态吗
     */
    private int code;
    /**
     * 返回的错误消息
     */
    private String msg;
    /**
     * 回调地址
     */
    private String callback;
    /**
     * 是否登陆
     */
    private Boolean logined = true;

    public Result() {
        this.isSuccess = true;
        this.code = ResultCode.RESULT_SUCCESS.getCode();
        this.msg = ResultCode.RESULT_SUCCESS.msg;
        this.callback = null;

    }

    public Result(int code) {
        this.code = code;
        this.msg = getResultCode(code).getMsg();
        if (code == ResultCode.RESULT_SUCCESS.getCode() || ResultCode.RESULT_SUCCESS.equals(code)) {
            this.isSuccess = true;
        } else {
            this.isSuccess = false;
        }
    }

    public Result(T data, Boolean isSuccess, int code, String msg, String callback, Boolean logined) {
        this.data = data;
        this.isSuccess = isSuccess;
        this.code = code;
        this.msg = msg;
        this.callback = callback;
        this.logined = logined;
    }

    public static Result success(int code) {
        return new Result(null, true, code, getResultCodeMsg(code), null, true);
    }

    public static Result success(Object ... obj) {
        ResultCode resultCode = ResultCode.RESULT_SUCCESS;
        return new Result(obj, true, resultCode.getCode(), resultCode.getMsg(), null, true);
    }

    public static Result fail(int code) {
        return new Result(null, false, code, getResultCodeMsg(code), null, true);
    }


    private ResultCode getResultCode(int code) {
        for (ResultCode resultCode : ResultCode.values()) {
            if (resultCode.getCode() == code || resultCode.equals(code)) {
                return resultCode;
            }
        }
        return ResultCode.RESULT_FAILED;
    }

    private static String getResultCodeMsg(int code) {
        for (ResultCode resultCode : ResultCode.values()) {
            if (resultCode.getCode() == code || resultCode.equals(code)) {
                return resultCode.getMsg();
            }
        }
        return "无效的错误码";
    }
}
